const router = require("koa-router")();
const JTW = require('jsonwebtoken')
const key = '34trfwaweferefw'
const userList = [
  {
    username: "admin",
    password: "admin",
    nickname: "管理员",
    avator: "https://robohash.org/123?set=set5",
    role: "admin",
  },
  {
    username: "user",
    password: "user",
    nickname: "有梦想程序猿",
    avator: "https://robohash.org/123124321?set=set5",
    role: "user",
  },
];

router.post("/login", (ctx) => {
  // 1. 获取传递过来的用户名和密码
  // ctx.request.query           get
  // ctx.request.body            post
  const { username, password } = ctx.request.body;
  // 2. 验证用户名和密码
  const user = userList.find(
    (v) => v.username === username && v.password === password
  );
  // 3. 返回用户名和密码
  if (user) {
    ctx.body = ({
      code: 200,
      message: "登录成功， 欢迎-" + user.nickname,
      data: {
        userInfo: user,
        token: JTW.sign(user, key)
      }
    });
  } else {
    ctx.body = ({
      code: 403,
      message: "账号密码错误， 请重新输入",
    });
  }
});

module.exports = router;
